/*
Copyright (c) 2009, Young Digital Planet SA
All rights reserved.

* Redistribution and use in source and binary forms, with or without 
  modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this 
  list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, 
  this list of conditions and the following disclaimer in the documentation 
  and/or other materials provided with the distribution.
* Neither the name of the Young Digital Planet SA nor the names of its 
  contributors may be used to endorse or promote products derived from this 
  software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
*/
package pl.ydp.nexl.impl.air
{
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.system.ApplicationDomain;
	import flash.system.SecurityDomain;
	
	import pl.ydp.nexl.INexlLibrary;
	import pl.ydp.nexl.impl.GatheringLibrary;
	import pl.ydp.nexl.impl.NexlLibrary;

	/**
	 * Nexl library that loads all plugins from given folder. If user calls 
	 * NexlFolderRegistry.loadPlugins class checks if application is run in
	 * testing environment. If it is, then NexlDebugFolderRegistry is used 
	 * to scan workspace and load all found nexl plugins.
	 * 
	 * @see pl.ydp.nexl.impl.air.NexlDebugFolderRegistry
	 */
	public class NexlFolderRegistry extends GatheringLibrary
	{
		internal var m_moduleAppDomain:ApplicationDomain;
		internal var m_moduleSecDomain:SecurityDomain;
		
		public function NexlFolderRegistry( appDomain:ApplicationDomain = null, secDomain:SecurityDomain = null ) {
			m_moduleAppDomain = appDomain==null ?
				new ApplicationDomain(ApplicationDomain.currentDomain) :
				appDomain;
			m_moduleSecDomain = secDomain;
		}
		
		public function load( libFolder:File, allowDirs:Boolean = true ):void {
			if ( !libFolder.isDirectory )
				return;
			
			var files:Array = libFolder.getDirectoryListing();
			for each( var f:File in files ) {
				if ( f.isDirectory && allowDirs )
					load( f, false );
				else if ( f.extension=="xml" ) {
					var stream:FileStream = new FileStream();
					stream.open( f, FileMode.READ );
					var xmlData:XML = new XML(stream.readUTFBytes(stream.bytesAvailable));
					stream.close();
					
					// throwing aout everything that is not library description
					if ( xmlData.localName()!="library" )
						continue;
					
					var swfFile:File;
					var libSwfPath:String = String(xmlData.@src);
					if ( libSwfPath!=null && libSwfPath.length>0 )
						swfFile = libFolder.resolvePath(libSwfPath);
					else {
						swfFile = libFolder.resolvePath(f.name.slice(0,-4)+".swf");
					} 
					
					trace("loading library: "+libFolder.name);
					this.addRegistry( loadLibrary(swfFile, f.parent, xmlData ) );
				}
			}
		}
		
		public function loadLibrary( libraryFile:File, baseFile:File, description:XML ):INexlLibrary {
			var app:File = new File( File.applicationDirectory.nativePath );
			if ( libraryFile.url.indexOf("app:")!=0 ) {
				var ext:File = File.applicationDirectory.resolvePath("externalLibs");
				if ( !ext.exists )
					new File(ext.nativePath).createDirectory();
				var eFile:File;
				for( var i:int=0; eFile==null && i<1000; ++i ) {
					eFile = ext.resolvePath( "ext"+i+".swf" );
					if ( eFile.exists )
						eFile = null;
				}
				libraryFile.copyTo( new File(eFile.nativePath),  true );
				libraryFile = eFile;
			}
			
			var lib:NexlLibrary = new NexlAirLibrary( libraryFile, baseFile, m_moduleAppDomain, m_moduleSecDomain );
			lib.loadData( description );
			return lib;
		}
		
		/**
		 * Removes externals folder and checks if application directory is bin or bin-debug.
		 * If it is not then this function works just like NexlFolderRegistry::loadFolder.
		 * Otherwise it is assumed that application runs in testing environment 
		 * and NexlDebugFolderRegistry is used to load plugins.
		 *
		 * @see pl.ydp.nexl.impl.air.NexlDebugFolderRegistry
		 * @param	folder
		 * @param	allowDebug
		 * @param	appDomain
		 * @param	secDomain
		 * @return
		 */
		public static function loadPlugins( folder:File, allowDebug:Boolean = true, appDomain:ApplicationDomain = null, secDomain:SecurityDomain = null ):INexlLibrary {
			cleanExternals();
			
			var app:File = File.applicationDirectory;
			if ( allowDebug && (app.name=="bin" || app.name=="bin-debug") ) {
				// testing in debug environment
				return NexlDebugFolderRegistry.loadFolder( folder,  appDomain, secDomain );
			} else {
				return NexlFolderRegistry.loadFolder( folder,  appDomain, secDomain );
			}
		}
		
		public static function loadFolder( folder:File, appDomain:ApplicationDomain = null, secDomain:SecurityDomain = null ):INexlLibrary {
			var fdrl:NexlFolderRegistry = new NexlFolderRegistry( appDomain, secDomain );
			fdrl.load( folder );
			
			return fdrl;
		}
		
		public static function cleanExternals():void {
			var ext:File = File.applicationDirectory.resolvePath("externalLibs");
			if ( ext.exists )
				new File(ext.nativePath).deleteDirectory(true);
		}
	}
}